﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

// UI上面展示模型
public class UIModel
{
    // 摄影棚
    private GameObject _modelStudioRoot;
    // 模型放置节点
    private GameObject _modelPlaceObj;
    // 模型节点初始旋转角度
    private Quaternion _srcModelRotation;
    // 摄像机节点
    private Camera _camera;

    public GameObject StudioRoot
    {
        get
        {
            return _modelStudioRoot;
        }
    }

    public void Create(RawImage targetImage, GameObject modelRoot)
    {
        // 生成一个摄影棚
        _modelStudioRoot = ResMgr.Instance.GetGameObject("Prefabs/UI/System/ModelStudio");
        _modelPlaceObj = _modelStudioRoot.FindComponent<Transform>("ModelPlace").gameObject;
        _srcModelRotation = _modelPlaceObj.transform.rotation;
        // 触摸旋转控制的节点
        //_RotateTouch.OnDragCallback = rotateObj;
        _camera = _modelStudioRoot.FindComponent<Camera>("Camera");
        RenderTexture target =
            new RenderTexture((int)targetImage.rectTransform.rect.width,
            (int)targetImage.rectTransform.rect.height, 24);
        _camera.targetTexture = target;
        targetImage.texture = target;

        modelRoot.transform.SetParent(_modelPlaceObj.transform, false);

        // 旋转
        var touch = targetImage.gameObject.AddComponent<Touch>();
        touch.OnDragCallback = onRotateModel;
    }

    internal void Release()
    {
        ResMgr.Instance.Release(_modelStudioRoot);
    }

    private void onRotateModel(PointerEventData eventData)
    {
        _modelPlaceObj.transform.Rotate(new Vector3(0, -eventData.delta.x, 0));
    }

}

// UI模型管理器
public class UIModelMgr : Singleton<UIModelMgr>
{
    private int _deltaX = 0;
    const int Distance = 10; // 两个UIModel之间的距离

    public UIModel CreatOneUIModel(RawImage targetImage, GameObject modelRoot)
    {
        var uimodel = new UIModel();
        uimodel.Create(targetImage, modelRoot);

        // 调整位置，使各个uimodel之间不可见
        uimodel.StudioRoot.transform.position += new Vector3(_deltaX, 0, 0);
        _deltaX += Distance;

        return uimodel;
    }

    public void Release(UIModel uiModel)
    {
        uiModel.Release();
    }
}
